<?php

namespace App\Http\Controllers\Index;
use Style,DB,Config;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\News\NewsImgExist;
use App\Models\News\News;
use App\Models\News\NewsCategory;

class NewsInfoController extends CommonController{

    /**
     * 资讯
     * @param $id
     * @return mixed
     */
    public function index($id)
    {
        //newsInfo
        $newsInfo = News::select('id','title','source','publisher','editorValue','style','readnum','updated_at')->where("id",$id)->first();
        if(!isset($newsInfo)){
            abort(404);
        }
        //讯息分类
        $firstClass = NewsCategory::select('id')->where('id',1)->first();
        $secondClass = NewsCategory::select('id','defectsname')->where('pid',$firstClass->id)->take(8)->get();
        //图标地址
        $categoryImg = [
            0 => '/default/images/index/nwes01.png',
            1 => '/default/images/index/nwes02.png',
            2 => '/default/images/index/nwes03.png',
            3 => '/default/images/index/nwes04.png',
            4 => '/default/images/index/nwes05.png',
            5 => '/default/images/index/nwes06.png',
            6 => '/default/images/index/nwes07.png',
            7 => '/default/images/index/nwes08.png'
        ];
        foreach($secondClass as $k => $v){
            //计算前十的阅读总合
            $readnum = DB::table('news')
                ->select(DB::raw('sum(readnum) as allcount'))
                ->where('category', '=', $v->id)
                ->orderBy('readnum','desc')
                ->take(10)
                ->first();
            $v->count = $readnum->allcount;
            $v->img = $categoryImg[$k];
        }
        //热门文章+这个月阅读量最高的文章
        $mon = date("Y-m-d H:i:s", strtotime(' -1 month', time()));
        //热点新闻第一张带图
        $hotNewsWithPic =  News::select('id','title','editorValue')->whereBetween('updated_at',[$mon,date('Y-m-d H:i:s')])
            ->whereHas('hotNewsWithPic',function($query){
                $query->where('img_state',1);
            })
            ->with(["hotNewsWithPic"=>function($query){
                $query->select('img_state');
            }])
            ->orderBy('readnum','desc')->first();

        if(!empty($hotNewsWithPic->editorValue)){
            if(preg_match_all('/<img(.*)?\s*src=\"(.*)\"(.*)\/>/Usi', $hotNewsWithPic->editorValue, $arr)){
                $hotNewsWithPic->imgUrl = $arr[2][0];//取出第一张
            }
        }

        $hotNews = News::select('id','title')->whereBetween('updated_at',[$mon,date('Y-m-d H:i:s')])
            ->orderBy('readnum','desc')
            ->take(9)->get();

        //阅读量
        News::where("id",$id)->increment('readnum');
        return Style::view("index.newsInfo",compact('secondClass','hotNewsWithPic','hotNews','newsInfo'));
    }
}